<template>
  <!-- 这是注册组件 -->
    <div class="label">
      <div>
        <van-nav-bar
            title="注册"
            left-text="返回"
            left-arrow
            @click-left="onClickLeft"
            @click-right="onClickRight"
            class="van-ellipsis"
            />
      </div>
      <div class="image" ></div>
      <van-form @submit="onSubmit" style="margin-top:3rem;">
        <!-- 用户名 -->
          <van-field
            v-model="uname"
            name="用户名"
            label="用户名"
            placeholder="请填写4位到10位汉字、字母或数字"
          />
          <!-- 密码 -->
           <van-field
            v-model="password"
            name="密码"
            label="密码"
            placeholder="请填写6位及以上字母或者数字"
          /> 
        <div style="margin: 16px;">
          <van-button @click="tijiao" round block type="info" native-type="submit">提交</van-button>
        </div>
      </van-form> 
  </div>
</template>
<style scoped>
.image{
  height:10rem;width:10rem;
  background-image: url(../../public/images/logo/1.jpg);
  background-repeat: no-repeat; 
  background-position: -11rem -4.4rem;
  position: relative;top:1rem;left: 30%;
}
#nav{
    position: relative;padding:0;
    margin-bottom: 3rem;
    
}
</style>
<script>
import { Toast } from 'vant';
export default {
  data() {
    return {
      uname: '',
      password: '',
    };
  },
  methods: {
    checkPwd(){
      let reg = /^\w{6,18}$/;
      if(reg.test(this.password)){ // 验证成功
        return true;
      }else{ // 验证失败
        return false;
      }
    },

    // 定义方法，验证用户名
    checkUname(){
      // 验证用户名  要求单词字符6~15位 [A-Za-z0-9_]
      let reg = /^[\u4e00-\u9fa5_a-zA-Z0-9_]{4,10}$/;
      if(reg.test(this.uname)){ // 验证成功
        return true;
      }else{ // 验证失败
        return false;
      }
    },
    tijiao(){
      if(this.checkUname()&&this.checkPwd()){
        this.axios.post('/user/register',
          `uname=${this.uname}&upwd=${this.password}`
          ).then(result=>{
            console.log(result)
          if(result.data.code==200){
            this.$notify({ type: 'success', message: '注册成功',duration: 1000, });
            this.$router.push('/login');
            }else if(result.data.code==201){
            this.$notify({ type: 'danger', message: '该用户名已被注册',duration: 1000, });
            }
          })
      }else{
        if((this.checkUname()==false)&&(this.checkPwd()==false)){
          this.$notify({ type: 'danger', message: '用户名和密码格式错误',duration: 1000, });
          return
        }
        if(!(this.checkUname())){
          this.$notify({ type: 'danger', message: '用户名格式错误',duration: 1000, });
          return
        }
        if(!(this.checkPwd())){
          this.$notify({ type: 'danger', message: '密码格式错误',duration: 1000, });
          return
        }
      }
    },
    onSubmit(errorInfo) {
        console.log('failed', errorInfo);
    },
    onClickLeft() {
      Toast('返回');
    },
    onClickRight() {
      Toast('按钮');
    },
  },

}
</script>
